package com.jfinal.club._admin.article;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Auther: 10091
 * @Date: 2018-07-13 16:32
 * @Description:
 */
public class TakeArticleUtil {
    static Logger logger  =  Logger.getLogger(TakeArticleUtil. class );
    private static String endpoint = "oss-cn-shanghai.aliyuncs.com";
    private static String accessKeyId = "UXuv5cqAv2ENbUTG";
    private static String accessKeySecret = "LUCijQdDKbM5hbiS9wI5e46cZwus2w";
    private static String bucketName = "lsege";

    //存放临时的阿里图片路径
    List<String> urls = new ArrayList<String>();

    public static void main(String [] args ){
       /* Document doc = null;
        try {
            doc = Jsoup.connect("http://www.huoxing24.com/newsauthor/01a70568381235638aa28b000b913c26/").get();
            //doc = Jsoup.connect("http://en.wikipedia.org/").get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.debug(doc.title());

        //Elements newsHeadlines = doc.select("#mp-itn b a");
        Elements newsHeadlines = doc.select("div .index-news-list");
        logger.debug(newsHeadlines.size());
        for (Element headline : newsHeadlines) {
           // logger.debug(headline.attr("title")+"----"+headline.absUrl("href") );
           // logger.debug(headline.attr("title")+"----"+headline.absUrl("href") );

            //标题
            Elements titles = headline.select("div .list-left a");

            logger.debug("title:"+titles.get(0).attr("title"));
            logger.debug("url:"+titles.get(0).absUrl("href"));
            //image
            Elements images = headline.select("div .list-left img");
            //logger.debug("images1:"+images.get(0).attr("src"));
            logger.debug("images2:"+images.get(0).absUrl("src"));
            //简介
            Elements details = headline.select("div .details");
            logger.debug("details:"+details.get(0).html());
        }*/

        try {
            //跳转详情页获取一下详细信息
            Document detaiDoc = Jsoup.connect("http://www.huoxing24.com/newsdetail/2018070613140691921.html").get();
            Elements contentElement = detaiDoc.select("div .detail-text-cont.simditor-body");
            String _contents = "";
            if (!contentElement.isEmpty()) {
                _contents = contentElement.get(0).html();
                // article.setContents(_contents);
                logger.debug(_contents);
               Elements pngs = contentElement.select("img[src]");
                for (Element element : pngs) {
                    String imgUrl = element.attr("src");
                    //if (imgUrl.trim().startsWith("/")) {
                        //imgUrl =HTTPHOST + imgUrl;
                        imgUrl = uploadHeadImg(imgUrl);
                        element.attr("src", imgUrl);
                   // }
                }
              String   newsBody = contentElement.toString();
              logger.debug(newsBody);
            }

        }catch (Exception e) {
                e.printStackTrace();
        }
    }


    public static String uploadHeadImg(String url) throws Exception {
        String imageName = imageName() + ".jpg";    //图片名称
        String path=new File("").getAbsolutePath()+"/";//这种方式可以拿到tomcat下的bin目录
        OSSClient  client = new OSSClient(endpoint, accessKeyId, accessKeySecret); //初始化上传客户端
        download(url, imageName, path);   //下载图片到本地（见下面）
        File file = new File(path + imageName);   //根据下载的文件创建新文件
        //文件不存在，则上传默认头像
        if (!file.exists()) {
            return "";
        }
        InputStream content = new FileInputStream(file);
        ObjectMetadata meta = new ObjectMetadata(); // 创建上传Object的Metadata
        meta.setContentLength(file.length());   // 必须设置ContentLength

        String keySuffixWithSlash ="toutiao/"+ folderNameYM() + "/" + folderNameD() + "/"; // 上传Object.（这里的方法是生成根据时间生成文件夹名称的）
        client.putObject(bucketName, keySuffixWithSlash + imageName, content, meta);  //图片上传到oss

        //String ossPath = ResourceUtil.getConfigByName("oss-domain") + keySuffixWithSlash + imageName;   //图片上传路径
       // String ossPath = ResourceUtil.getConfigByName("oss-domain") + keySuffixWithSlash + imageName;   //图片上传路径
        String ossPath ="https://lsege.oss-cn-shanghai.aliyuncs.com/" + keySuffixWithSlash + imageName;   //图片上传路径
        if (file.exists()) {//上传完成后，删除文件
                file.delete();
        }
        content.close();//关闭所有链接
        client.shutdown();
        return ossPath;
    }

    /**
     * 下载图片到本地
     *
     * @param urlString
     * @param filename
     * @param savePath
     * @throws Exception
     */
    public static void download(String urlString, String filename, String savePath) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为5s
        con.setConnectTimeout(5 * 1000);
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf = new File(savePath);
        if (!sf.exists()) {
            sf.mkdirs();
        }
        OutputStream os = new FileOutputStream(sf.getPath() + "/" + filename);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }


    /**
     * 文件夹名称-年月
     *
     * @return
     */
    public static String folderNameYM() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
        String strDate = formatter.format(new Date());
        return strDate;
    }

    /**
     * 文件夹名称-天
     *
     * @return
     */
    public static String folderNameD() {
        SimpleDateFormat formatter = new SimpleDateFormat("dd");
        String strDate = formatter.format(new Date());
        return strDate;
    }

    /**
     * 图片名称生成
     *
     * @return
     */
    public static String imageName() {
        Random random = new Random();//生成随机数
        String strDate = Long.toString(System.currentTimeMillis());
        for (int i = 0; i < 3; i++) {
            strDate = strDate + random.nextInt(9);
        }
        return strDate;
    }
}
